<template>
  <div>

    <el-row>
      <el-col :span="3">
        <el-button type="primary" @click="dialogVisible = true" icon="el-icon-plus">新增</el-button>
      </el-col>
      <el-col :span="7">
        <el-input placeholder="请输入真实姓名" v-model="searcher.name" clearable @clear="list">
          <el-button slot="append" icon="el-icon-search" @click="query"></el-button>
        </el-input>
      </el-col>
    </el-row>

    <!-- 列表数据 -->
    <el-table :data="pageResult.list" stripe border>
      <el-table-column prop="name" label="账号"></el-table-column>
      <el-table-column prop="realName" label="真实姓名"></el-table-column>
      <el-table-column prop="roles" label="角色">
        <template slot-scope="scope">
          <el-tag v-for="item in scope.row.roles" :label="item" :key='item' size="medium">{{item}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="statusValue" label="状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.statusBool" @change="statusChange(scope.row.id, scope.row.statusBool)" :disabled="scope.row.id===1"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" size="mini" @click="get(scope.row.id)">编辑</el-button>
          <el-button v-if="scope.row.id!==1" type="text" icon="iconfont icon-password" size="mini" @click="showPwdDialog(scope.row.id)">密码</el-button>
          <el-button v-if="scope.row.id!==1" type="text" icon="el-icon-delete" size="mini" @click="remove(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                   :current-page="pageResult.pageNum" :page-size="pageResult.pageSize" :total="pageResult.total"
                   :page-sizes="[5, 10]" layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>

    <!-- 模态 -->
    <el-dialog title="用户" :visible.sync="dialogVisible" width="30%" @close="closeDialog">
      <!-- 主体 -->
      <el-form ref="itemRef" :model="item" :rules="itemRules" label-width="80px">
        <el-form-item label="帐号" prop="name">
          <el-input v-model="item.name" clearable :disabled="this.item.id===1"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="item.realName" clearable></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleList">
          <el-checkbox-group v-model="item.roleList" :disabled="this.item.id===1">
            <el-checkbox v-for="item in roleList" :label="item.id" :key='item.id' name="type">{{item.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="postData">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 重置密码模态 -->
    <el-dialog title="重置密码" :visible.sync="passwordDialogVisible" width="30%" @close="closePwdDialog">
      <!-- 主体 -->
      <el-form ref="passwordRef" :model="passwordItem" :rules="passwordRules" label-width="80px">
        <el-form-item label="新密码" prop="password">
          <el-input v-model="passwordItem.password" type="password" clearable></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="passwordDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updatePassword">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data () {
    // 账号校验规则
    let checkName = (rule, value, callback) => {
      this.$axios.post('/user/checkName', { id: this.item.id, name: value })
        .then((res) => {
          if (res.data.data) {
            callback(new Error('该账号已存在'))
          } else {
            callback()
          }
        })
    }
    return {
      // 查询条件
      searcher: {
        pageNum: 1,
        pageSize: 10,
        name: ''
      },
      // 分页结果
      pageResult: {
        // 分页列表数据
        list: [],
        // 数据总条数
        total: 0,
        // 数据总页数
        pages: 0,
        // 当前页
        pageNum: 1,
        // 当前分页条数
        pageSize: 10
      },
      // 模态显示
      dialogVisible: false,
      passwordDialogVisible: false,
      // 用户
      item: {
        id: 0,
        name: '',
        realName: '',
        roleList: []
      },
      passwordItem: {
        id: 0,
        password: ''
      },
      // 用户模态校验
      itemRules: {
        name: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 1, max: 10, message: '账号在 1 到 10 个字符之间', trigger: 'blur' },
          { validator: checkName, trigger: 'blur' }
        ],
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' },
          { min: 1, max: 10, message: '真实姓名在 1 到 10 个字符之间', trigger: 'blur' }
        ],
        roleList: [
          { type: 'array', required: true, message: '请至少选择一个角色', trigger: 'change' }
        ]
      },
      // 重置密码模态
      passwordRules: {
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '密码在 6 到 16 个字符之间', trigger: 'blur' }
        ]
      },
      // 所有角色
      roleList: []
    }
  },
  created () {
    this.list()
    this.listAllRole()
  },
  methods: {
    async list () {
      const { data } = await this.$axios.post('/user/list', this.searcher)
      this.pageResult = data
    },
    // 注意，switch 回调值为变更后的值
    async statusChange (id, statusBool) {
      console.log('id: ' + id + ', status: ' + statusBool)
      let requestUrl
      if (statusBool) {
        requestUrl = '/user/unlock'
      } else {
        requestUrl = '/user/lock'
      }
      const { data } = await this.$axios.post(requestUrl, { id: id })
      this.$message.success(data.msg)
    },
    // 查询, 每次查询，从第 1 页开始展示数据
    query () {
      this.searcher.pageNum = 1
      this.list()
    },
    // 分页每页展示数据量变更
    handleSizeChange (crrentPageSize) {
      this.searcher.pageSize = crrentPageSize
      this.list()
    },
    // 分页当前页码变更
    handleCurrentChange (currentPage) {
      this.searcher.pageNum = currentPage
      this.list()
    },
    // 模态关闭
    closeDialog () {
      // 重置校验
      this.$refs.itemRef.resetFields()
    },
    // 用户详情
    async get (id) {
      const { data } = await this.$axios.post('/user/get', { id: id })
      this.item = data.data
      this.dialogVisible = true
    },
    // 提交修改
    async postData () {
      this.$refs.itemRef.validate(async valid => {
        if (valid) {
          let requestUrl
          if (this.item.id) {
            requestUrl = '/user/update'
          } else {
            requestUrl = '/user/save'
          }
          const { data } = await this.$axios.post(requestUrl, this.item)
          // 后续操作：弹窗、关模态、刷新分页、清空表单数据
          this.$message.success(data.msg)
          this.dialogVisible = false
          this.list()
          this.closeDialog()
        }
      })
    },
    // 重置密码模态显示
    showPwdDialog (id) {
      this.passwordDialogVisible = true
      this.passwordItem.id = id
    },
    // 重置密码模态关闭
    closePwdDialog () {
      // 重置校验
      this.$refs.passwordRef.resetFields()
    },
    // 重置密码
    updatePassword () {
      this.$refs.passwordRef.validate(async valid => {
        if (valid) {
          const { data } = await this.$axios.post('/user/updatePwd', this.passwordItem)
          // 后续操作：弹窗、关模态、刷新分页、清空表单数据
          this.$message.success(data.msg)
          this.passwordDialogVisible = false
          this.list()
          this.closePwdDialog()
        }
      })
    },
    // 删除用户, confirm
    async remove (id) {
      const confirmResult = await this.$confirm('将删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult === 'confirm') {
        const { data } = await this.$axios.post('/user/delete', { id: id })
        this.$message.success(data.msg)
        this.list()
      }
    },
    // 所有角色
    async listAllRole () {
      const { data } = await this.$axios.post('/role/listAll')
      this.roleList = data.data
    }
  }
}
</script>

<style lang="less" scoped>

</style>
